﻿@{
    ViewBag.Title = "CategoryList";
    Layout = "~/Areas/Shared/_spList.cshtml";
}
@model Kaiser.Modules.Hiner.Models.Product.Attachment
<div region="center" border="false" style="width: 500px; height: 300px; margin: 1px;
    padding: 0px; overflow-y: hidden">
    <div id="grid">
    </div>
</div>
<script src="@Url.Content("~/Scripts/upload/ajaxfileupload.js")" type="text/javascript"></script>
<script type="text/javascript">
    // 全局变量
    var grid;
    var dlg_Edit;
    var dlg_Edit_form;
    var searchWin;
    var searchForm;
    var virpath = ""; //网站的虚拟目录 如：/ShopManager
    var config = {
        ListActionURL: '@Url.Action("UploadFilesList", "ProductManage", new { area = "Hiner" })',
        AddActionURL: '@Url.Action("AddCategoryDetail", "Category", new { area = "Hiner" })',
        DelActionURL: '@Url.Action("DelAttachment", "ProductManage", new { area = "Hiner" })'
    };



    $(function () {
        $(window).resize(function () {
            $('#grid').datagrid('resize');
        });


        grid = $('#grid').datagrid({
            title: '上传管理',
            iconCls: 'icon-save',
            methord: 'post',
            url: config.ListActionURL,

            method: 'post',
            sortName: 'Sequence',
            sortCategory: 'Sequence',
            idField: 'Id',
            pageSize: 10,
            striped: true,

            frozenColumns: [[
	                { field: 'ck', checkbox: true }
				]],
            columns: [[
					{ field: 'Attach_FileName', title: '附件名称', sortable: true },
                    { field: 'Attach_ContentType', title: '附件类型', sortable: true },
                    { field: 'Attach_Size', title: '附件大小', sortable: true },
                    { field: 'Attach_CreateTime', title: '创建时间', sortable: true, formatter: ChangeDateFormat }
				]],
            fit: true,
            pagination: true,
            rownumbers: true,
            fitColumns: true,
            singleSelect: false,
            toolbar: [{
                text: '上传',
                iconCls: 'icon-add',
                handler: add
            }, '-', {
                text: '删除',
                iconCls: 'icon-remove',
                handler: del
            }], onDblClickRow: function (rowIndex, rowData) {  //双击事件
                $.messager.confirm('提示信息', '您确认要删除选中的所有记录吗?', function (data) {
                    if (data) {
                        $.ajax({
                            url: virpath + config.DelActionURL + '?ids=' + rowData.Attach_ID,
                            type: 'post',
                            error: function (result) {

                                Msgalert('错误', '删除失败!' + result.statusText, 'error');
                                grid.datagrid('clearSelections');
                            },
                            success: function (result) {
                                var data = eval('(' + result + ')');
                                if (data.success) {
                                    Msgfade(arr.length + "条记录" + data.msg); //提示消息
                                    grid.datagrid('reload');
                                    grid.datagrid('clearSelections');
                                } else {
                                    Msgalert('错误', data.msg, 'error');
                                }
                            }
                        });
                    }
                });

            }, onHeaderContextMenu: function (e, field) {
                e.preventDefault();
                if (!$('#tmenu').length) {
                    createColumnMenu();
                }
                $('#tmenu').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }

        });

        dlg_Edit = $('#Dlg-Edit').dialog({
            closed: true,
            modal: true,
            toolbar: [{
                text: '关闭',
                iconCls: 'icon-no',
                handler: function () {
                    dlg_Edit.dialog('close');
                }
            }]

        });
        dlg_Edit_form = dlg_Edit.find('form');

        $('#btn-search,#btn-search-cancel').linkbutton();
        searchWin = $('#search-window').window({
            iconCls: 'icon-search',
            closed: true,
            modal: true
        });
        searchForm = searchWin.find('form');

        $('body').layout();

    });

    function ChangeDateFormat(jsondate, row, index) {
        if (jsondate != undefined) {
            jsondate = jsondate.replace("/Date(", "").replace(")/", "");
            if (jsondate.indexOf("+") > 0) {
                jsondate = jsondate.substring(0, jsondate.indexOf("+"));
            }
            else if (jsondate.indexOf("-") > 0) {
                jsondate = jsondate.substring(0, jsondate.indexOf("-"));
            }

            var date = new Date(parseInt(jsondate, 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
        return "";
    }

    function createColumnMenu() {
        var tmenu = $('<div id="tmenu" style="width:100px;"></div>').appendTo('body');
        var fields = grid.datagrid('getColumnFields');
        for (var i = 0; i < fields.length; i++) {
            $('<div iconCls="icon-ok"/>').html(fields[i]).appendTo(tmenu);
        }
        tmenu.menu({
            onClick: function (item) {
                if (item.iconCls == 'icon-ok') {
                    grid.datagrid('hideColumn', item.text);
                    tmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    grid.datagrid('showColumn', item.text);
                    tmenu.menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
    }

    //获取ID数组 
    function getSelectedArr() {
        var ids = [];
        var rows = $('#grid').datagrid('getSelections');
        for (var i = 0; i < rows.length; i++) {
            ids.push(rows[i].Attach_ID);
        }
        return ids;
    }
    //获取ID
    function getSelectedID() {
        var ids = getSelectedArr();
        return ids.join(',');
    }
    function arr2str(arr) {
        return arr.join(',');
    }

    function add() {
        dlg_Edit_form.form('clear');
        dlg_Edit.dialog('open');
        dlg_Edit.dialog('setTitle', '分类管理');
        $("#CategoryDetailCode").val(NewGuid());
        dlg_Edit_form.url = virpath + config.AddActionURL;

        //Msgalert("提示", '成功调用', "info");    
    }
    //    function edit() {
    //        var rows = grid.datagrid('getSelections');
    //        var num = rows.length;
    //        if (num == 0) {
    //            Msgshow('请选择一条记录进行操作!');
    //            //$.messager.alert('提示', '请选择一条记录进行操作!', 'question');       
    //            return;
    //        }
    //        else if (num > 1) {
    //            Msgfade('您选择了多条记录,只能选择一条记录进行修改!'); //$.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info');
    //            return;
    //        }
    //        else {
    //            dlg_Edit_form.form('clear');
    //            dlg_Edit.dialog('open');
    //            dlg_Edit.dialog('setTitle', '您正在修改' + rows[0].CategoryName + '分类');
    //            dlg_Edit_form.form('load', rows[0]); //加载到表单的控件上
    //            dlg_Edit_form.url = virpath + config.EditActionURL + '?id=' + rows[0].ID;
    //        }
    //    }
    function del() {
        var arr = getSelectedArr();
        //   alert(arr);
        // return false;
        if (arr.length > 0) {
            $.messager.confirm('提示信息', '您确认要删除选中的所有记录吗?', function (data) {
                if (data) {
                    $.ajax({
                        url: virpath + config.DelActionURL + '?ids=' + arr2str(arr),
                        type: 'post',
                        error: function (result) {

                            Msgalert('错误', '删除失败!' + result.statusText, 'error');
                            grid.datagrid('clearSelections');
                        },
                        success: function (result) {
                            var data = eval('(' + result + ')');
                            if (data.success) {
                                Msgfade(arr.length + "条记录" + data.msg); //提示消息
                                grid.datagrid('reload');
                                grid.datagrid('clearSelections');
                            } else {
                                Msgalert('错误', data.msg, 'error');
                            }
                        }
                    });
                }
            });
        } else {
            Msgshow('请先选择要删除的记录。');

        }
    }
    function saveData() {

        //alert(dlg_Edit_form.url);
        dlg_Edit_form.form('submit', {
            url: dlg_Edit_form.url,
            onSubmit: function () {
                return $(this).form('validate');
            },
            success: function (result) {
                successCallback(result);

            }
        });
    }
    function showAll() {
        grid.datagrid({ url: virpath + config.ListActionURL });
    }

    function OpensearchWin() {
        searchWin.window('open');
        searchForm.form('clear');
    }
    function SearchOK() {
        var ProductName = $("#S_ProductName").val();
        searchWin.window('close');
        grid.datagrid({ url: virpath + config.ListActionURL, queryParams: { ProductName: ProductName} });
    }

    function closeSearchWindow() {
        searchWin.window('close');
    }




    function showImage() {
        var o = $("#fileToUpload").get(0);
        if (!/\.((jpg)|(bmp)|(gif)|(png))$/ig.test(o.value)) {
            alert('只能上传jpg,bmp,gif,png格式图片!');
            o.outerHTML = o.outerHTML;
            return false;
        }
        else {
            $("#buttonUpload").click();
        }

    }

    //获取file完整路径
    function getFullPath() {
        var obj = document.getElementById("fileToUpload");
        if (obj) {
            if (window.navigator.userAgent.indexOf("MSIE") >= 1)    //ie  
            {
                obj.select();
                obj.blur();
                return document.selection.createRange().text;
            }
            else if (window.navigator.userAgent.indexOf("Firefox") >= 1)             //firefox  
            {
                if (obj.files) {
                    return obj.files.item(0).getAsDataURL();
                }
                return obj.value;
            }
            return obj.value;
        }
    }
    $("#ImageTd").hide();
    //上传
    function ajaxFileUpload() {
        $("#loading")
        .ajaxStart(function () {
            $(this).show();
        })
        .ajaxComplete(function () {
            $(this).hide();
        });

        $.ajaxFileUpload
        (
            {
                url: '@Url.Action("UploadFiles", "ProductManage", new { area = "Hiner" })?ObjectID=' + "111" + '&ObjectModule=' + "Hinner",
                secureuri: false,
                fileElementId: 'fileToUpload',
                dataType: 'json',
                success: function (data, status) {
                    if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            alert(data.msg);
                        }
                    }
                    else {
                        $("#ImageTd").show();
                        // $("#ImageTd").append("<img style='width:50px;height:50px;' src='" + data.msg + "'  /> ");
                        $("#ProductImgUrl").val(data.msg);
                        $("#ImageTd").attr("src", data.msg);

                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            }
        )

        return false;
    }
</script>
<div style="display: none">
    <div id="Dlg-CategoryTree" style="width: 350px; height: 220px;">
        <ul class="easyui-tree" id="SelectCategoryTree">
        </ul>
    </div>
    <div id="Dlg-Edit" title="编辑" style="width: 600px; height: 400px;" buttons="#buttons">
        <div style="padding: 10px">
            <form method="post">
            <table>
                <tr>
                    <td style="text-align: right">
                        图片：
                    </td>
                    <td>
                        <!--id="ImageTd"-->
                        <input id="fileToUpload" type="file" size="45" name="fileToUpload" onchange="showImage(this)">
                        <input type="button" id="buttonUpload" value="上传" style="display: none;" onclick="return ajaxFileUpload();">
                        </br>
                        @Html.HiddenFor(m => Model.Attach_Path)
                        <img id="ImageTd" width="120px" height="120px" />
                    </td>
                </tr>
            </table>
            </form>
        </div>
    </div>
</div>
